package com.wen.web;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebView;
import com.wen.web.init.WebChromeClientImpl;
import com.wen.web.init.WebViewInitializer;

import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;

import cn.wen.core.titlebar.DefTitleBar;
import cn.wen.core.ui.AppActivity;


/**
 * 封装的WebActivity
 */

public class WebActivity extends AppActivity implements WebChromeClientImpl.OpenFileChooserListener {

    public static final String WEB_DATA = "WebData";
    private FrameLayout mFlWebContainer;
    private final ReferenceQueue<WebView> WEB_VIEW_QUEUE = new ReferenceQueue<>();
    private WebViewInitializer mWebViewInitializer;
    private WebView mWebView;
    private ProgressWebView mProgressWebView;
    /**
     * JS注入的名称
     */
    private static final String JS_NAME = "appCarB";
    /**
     * 打开页面传递过来的参数
     */
    private WebData mWebData;
    /**
     * 打开相册 本地文件等等
     */
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;


    @Override
    protected Object getContentLayout() {
        return R.layout.act_web;
    }

    @Override
    protected void initData(Bundle bundle) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE | WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        mWebData = (WebData) getIntent().getSerializableExtra(WEB_DATA);
        mWebViewInitializer = new WebViewInitializer(this, this);
        initWebView();
    }

    @SuppressLint("JavascriptInterface")
    private void initWebView() {
        if (mWebView != null) {
            mWebView.removeAllViews();
        } else {
            mProgressWebView = new ProgressWebView(this);
            final WeakReference<WebView> webViewWeakReference = new WeakReference<>(mProgressWebView.getWebView(), WEB_VIEW_QUEUE);
            mWebView = webViewWeakReference.get();
            mWebView = mWebViewInitializer.initWebView(mWebView);
            mWebView.setWebViewClient(mWebViewInitializer.initWebViewClient());
            mWebView.setWebChromeClient(mWebViewInitializer.initWebChromeClient());
            // 注入JS交互
            mWebView.addJavascriptInterface(WebJSInterface.create(this), JS_NAME);
        }

    }

    @Override
    protected void initTitle(DefTitleBar titleBar) {
        if (mTitleBar != null) {
            mTitleBar.setTitleLeftRightPadding(50);
            if (mWebData != null && !TextUtils.isEmpty(mWebData.title)) {
                mTitleBar.setTitle(mWebData.title);
            }
        }
    }

    @Override
    protected void initView(View view) {
        mFlWebContainer = findViewById(R.id.fl_web_container);
        mWebViewInitializer.setOnWebChromeListener(new WebChromeClientImpl.OnWebChromeListener() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                if (mTitleBar != null) {
                    if (mWebData != null && !TextUtils.isEmpty(mWebData.title)) {
                        return;
                    }
                    mTitleBar.setTitle(title + "");
                }
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (mProgressWebView == null) {
                    return;
                }
                ProgressBar progressbar = mProgressWebView.getProgressbar();
                if (progressbar == null) {
                    return;
                }
                if (newProgress == 100) {
                    progressbar.setVisibility(View.GONE);
                } else {
                    if (progressbar.getVisibility() == View.GONE) {
                        progressbar.setVisibility(View.VISIBLE);
                    }
                    progressbar.setProgress(newProgress);
                }
            }
        });
        if (mFlWebContainer.getChildCount() > 0) {
            mFlWebContainer.removeAllViews();
        }
        mFlWebContainer.addView(mProgressWebView);
        // 加载URL
        if (mWebView != null && mWebData != null) {
            // 跳转并进行页面加载
            WebManager.getInstance().loadPage(mWebView, mWebData.url);
        }
    }


    @Override
    public void onPause() {
        if (mWebView != null) {
            mWebView.onPause();
        }
        super.onPause();
    }

    @Override
    public void onResume() {
        if (mWebView != null) {
            mWebView.onResume();
        }
        super.onResume();
    }


    @Override
    public void onDestroy() {
        if (mFlWebContainer != null && mWebView != null) {
            mWebView = null;
            mProgressWebView = null;
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mWebView != null && (keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
            mWebView.goBack(); // 浏览网页历史记录 goBack()和goForward()
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    /**
     * 打开相册 本地文件等等
     */
    @Override
    public void openFileChooser(ValueCallback<Uri> uploadMsg, ValueCallback<Uri[]> filePathCallback) {
        uploadFile = uploadMsg;
        uploadFiles = filePathCallback;
        openFileChooseProcess();
    }

    /**
     * 打开相册 本地文件等等
     */
    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "请选择"), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != uploadFile) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFiles.onReceiveValue(new Uri[]{result});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }
            if (uploadFiles != null) {
                uploadFiles.onReceiveValue(null);
                uploadFiles = null;
            }
        }
    }
}
